package net.cmkj.mine.core.admin.module;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import net.cmkj.mine.bean.*;
import net.cmkj.mine.common.anno.RequiresPermissions;
import net.cmkj.mine.common.controller.BaseController;
import net.cmkj.mine.common.model.DataGridModel;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.DataGridModelUtils;
import net.cmkj.mine.util.IWebUtils;

import java.util.List;

public class ModulesController extends BaseController {
	
	@Inject
	private ModulesService service;

	@RequiresPermissions(value={"/modules"})
	public void index() throws Exception {
		render("modulesList.html");
	}
	
	@RequiresPermissions(value={"/modules"})
	public void columns() throws Exception {
		String tablename = getPara("tablename");
		setAttr("tablename", tablename);
		long moduleid = getParaToLong("moduleid");
		setAttr("moduleid", moduleid);
		//setAttr("count", service.getColumnsList(tablename).getCount());
		setAttr("count", service.getColumnCount(moduleid));
		render("columnsList.html");
	}
	
	@RequiresPermissions(value={"/modules"})
	public void form() throws Exception {
		Long id = getParaToLong("id");
		if(id != null){
			setAttr("item", service.findById(id));
		}
		setAttr("types", DictData.dao.getData("columntype"));
		setAttr("sysRes", SysRes.dao.getData());
		render("modulesForm.html");
	}

    @RequiresPermissions(value={"/modules"})
    public void edit() throws Exception {
        Long id = getParaToLong("id");
        if(id != null){
            Modules modules = service.findById(id);
            setAttr("item", modules);
            setAttr("pid", SysRes.dao.findById(modules.getSysres()).getPid());
        }
        setAttr("types", DictData.dao.getData("columntype"));
        setAttr("sysRes", SysRes.dao.getData());
        render("modulesEdit.html");
    }

	@RequiresPermissions(value={"/modules"})
	public void getList() throws Exception {
		String name = getPara("name");
		Integer status = getParaToInt("status");
		renderJson(service.getList(getPage(), getRows(), name, status, getOrderbyStr()));
	}

	@RequiresPermissions(value={"/modules"})
	public void getColumnsList() throws Exception {
		//String tablename = getPara("tablename");
		long moduleid = getParaToLong("moduleid");
		String name = getPara("name");
		Integer status = getParaToInt("status");
		renderJson(service.getColumnsList(getPage(), getRows(), moduleid, name, status, " order by t.ordinal_position"));
	}

	@RequiresPermissions(value={"/modules"})
	public void save() throws Exception {
		String[] column_comments = getParaValues("column_comment");
		String[] column_types = getParaValues("column_type");
		Long[] foreignTables = getParaValuesToLong("foreignTable");
		String[] foreignKeys = getParaValues("foreignKey");
		Integer[] lengths = getParaValuesToInt("length");
		Integer[] decimals = getParaValuesToInt("decimal");
		String[] column_defaults = getParaValues("column_default");
		String[] is_nullables = getParaValues("is_nullable");
        Integer pid = getParaToInt("pid");
        renderJson(service.save(getModel(Modules.class), IWebUtils.getCurrentSysUser(getRequest()), column_comments, column_types, foreignTables, foreignKeys, lengths, decimals, column_defaults, is_nullables,pid));
	}

	@RequiresPermissions(value={"/modules"})
	public void update() throws Exception {
		Integer pid = getParaToInt("pid");
		renderJson(service.update(getModel(Modules.class),pid,IWebUtils.getCurrentSysUser(getRequest())));
	}
	
	@RequiresPermissions(value={"/modules"})
	public void delete() throws Exception {
		renderJson(service.delete(getPara("ids"),IWebUtils.getCurrentSysUser(getRequest())));
	}
	
	@RequiresPermissions(value={"/modules"})
	public void setStatus() throws Exception {
		String ids = getPara("ids");
		Integer status = getParaToInt("status");
		renderJson(service.setStatus(ids, status,IWebUtils.getCurrentSysUser(getRequest())));
	}

	@RequiresPermissions(value={"/modules"})
	public void setColumnShow() throws Exception {
		String ids = getPara("ids");
		Integer isshow = getParaToInt("isshow");
		renderJson(service.setColumnShow(ids, isshow));
	}

	@RequiresPermissions(value={"/modules"})
	public void searchForm() throws Exception {
		setAttr("moduleid", getParaToLong("moduleid"));
		render("searchForm.html");
	}

	@RequiresPermissions(value={"/modules"})
	public void getSearchList() throws Exception {
		long moduleid = getParaToLong("moduleid");
		renderJson(service.getColumnsList(moduleid));
	}

	@RequiresPermissions(value={"/modules"})
	public void getSearchedList() throws Exception {
		long moduleid = getParaToLong("moduleid");
		renderJson(service.getSearchedList(moduleid));
	}

	@RequiresPermissions(value={"/modules"})
	public void saveColumnsSearch() throws Exception {
		long moduleid = getParaToLong("moduleid");
		String data = getPara("data");
		renderJson(service.saveColumnsSearch(moduleid, data));
	}

	@RequiresPermissions(value={"/modules"})
	public void createTable() throws Exception {
		String[] column_comments = getParaValues("column_comment");
		String[] column_types = getParaValues("column_type");
		Integer[] lengths = getParaValuesToInt("length");
		Integer[] decimals = getParaValuesToInt("decimal");
		String[] column_defaults = getParaValues("column_default");
		String[] is_nullables = getParaValues("is_nullable");
		renderJson(service.createTable(column_comments, column_types, lengths, decimals, column_defaults, is_nullables));
	}
	
	@RequiresPermissions(value={"/modules"})
	public void columnsForm() throws Exception {
		String tablename = getPara("tablename");
		String target = getPara("target");
		if (CommonUtils.isNotEmpty(target)) {
			setAttr("target", target);
		}
		String column_name = getPara("column_name");
		if (CommonUtils.isNotEmpty(column_name)) {
			setAttr("column_name", column_name);
			//setAttr("column", service.getColumn(tablename, "column_name", column_name));
			long id = getParaToLong("id");
			setAttr("column", service.findColumnsById(id));
		}
		setAttr("moduleid", getParaToLong("moduleid"));
		setAttr("tablename", tablename);
		render("columnsForm.html");
	}
	
	@RequiresPermissions(value={"/modules"})
	public void saveColumns() throws Exception {
		long moduleid = getParaToLong("moduleid");
		String tablename = getPara("tablename");
		String target = getPara("target");
		String column_comment = getPara("column_comment");
		String column_type = getPara("column_type");
		int length = getParaToInt("length", 0);
		Integer decimal = getParaToInt("decimal");
		String column_default = getPara("column_default");
		String is_nullable = getPara("is_nullable");
		Long foreignTable = getParaToLong("foreignTable");
		String foreignKey = getPara("foreignKey");
		if ("on".equalsIgnoreCase(is_nullable)) {
			is_nullable = "YES";
		} else {
			is_nullable = "NO";
		}
		String column_name = getPara("column_name");
		if (CommonUtils.isNotEmpty(column_name)) {
			renderJson(service.editColumns(moduleid, tablename, column_name, column_comment, column_type, length, decimal, column_default, is_nullable, foreignTable, foreignKey));
		} else {
			renderJson(service.addColumns(moduleid, tablename, target, column_comment, column_type, length, decimal, column_default, is_nullable, foreignTable, foreignKey));
		}
	}

    @RequiresPermissions(value={"/modules"})
    public void deleteColumns() throws Exception {
        renderJson(service.deleteColumns(getPara("ids"),getPara("tablename")));
    }
	
	@RequiresPermissions(value={"/modules"})
	public void move() throws Exception {
		long columnid = getParaToLong("columnid");
		String tablename = getPara("tablename");
		String column = getPara("column");
		Integer updown = getParaToInt("updown");
		renderJson(service.move(columnid, tablename, column, updown));
	}

	@RequiresPermissions(value={"/modules"})
	public void getForeignTables() throws Exception {
		Long moduleid = getParaToLong("moduleid");
		renderJson(service.getForeignTables(moduleid));
	}

    /**
     *模块分配数据权限
     */
    @RequiresPermissions(value={"/modules"})
    public void competence() throws Exception {
		Long id = getParaToLong("id");
		if(id != null){
			Modules modules = service.findById(id);
			setAttr("item", modules);
			setAttr("pid", SysRes.dao.findById(modules.getSysres()).getPid());
		}
        render("competence.html");
    }

    /**
     *模块分配权限
     */
    @RequiresPermissions(value={"/modules"})
    public void userCompetence() throws Exception {
        Long moduleid = getParaToLong("moduleid");
        Page<ModuleUser> paginate = ModuleUser.dao.paginate(getPage(), getRows(),moduleid,getOrderbyStr());
        DataGridModel result = DataGridModelUtils.toDataGridView(paginate);
        renderJson(result);
    }

    /**
     *保存用户权限
     */
    @RequiresPermissions(value={"/modules"})
    public void saveCompetence() throws Exception {
        Long userid = getParaToLong("userid");
        Long moduleid = getParaToLong("moduleid");
        Integer type = getParaToInt("type");
        renderJson(service.saveCompetence(userid,moduleid,type));
    }

    /**
     *删除用户权限
     */
    @RequiresPermissions(value={"/modules"})
    public void deleteCompetence() throws Exception {
        Long competenceid = getParaToLong("id");
        renderJson(ModuleUser.dao.findById(competenceid).delete());
    }

    @RequiresPermissions(value={"/modules"})
    public void updateCompetence() throws Exception {
        Long competenceid = getParaToLong("competenceid");
        Long userid = getParaToLong("userid");
        Long moduleid = getParaToLong("moduleid");
        Integer type = getParaToInt("type");
        renderJson(service.updateCompetence(competenceid,userid,moduleid,type));
    }

    /**
     *模块分配菜单权限
     */
    @RequiresPermissions(value={"/modules"})
    public void menuCompetence() throws Exception {
        Long id = getParaToLong("id");
        if(id != null){
            Modules module = Modules.dao.findById(id);
            setAttr("module", module);
            setAttr("restree", SysUser.dao.getZtreeViewList(1, module.getSysres()));
        }
        render("userModule.html");
    }

    @RequiresPermissions(value={"/modules"})
    public void saveModuleUser() throws Exception {
        //Integer resId=getParaToInt("resId");
		String resId=getPara("resId");
        String userIds=getPara("userIds");
        renderJson(service.saveModuleUser(resId, userIds));
    }

	/**
	 *自定义排序
	 */
	@RequiresPermissions(value={"/modules"})
	public void order() throws Exception {
		Long id = getParaToLong("id");
		if(id != null){
			Modules modules = service.findById(id);
            setAttr("item", modules);
		}
		render("orderby.html");
	}

    @RequiresPermissions(value={"/modules"})
    public void getColumns() throws Exception {
        Integer moduleid=getParaToInt("moduleid");
        List<Record> columns = Db.find("SELECT t.id,t.column_comment as name FROM `columns` t WHERE t.moduleid = " + moduleid + " and t.column_type IN ( 'int', 'double', 'date', 'varchar' ) and t.id not in (SELECT columnsid from t_order where moduleid = " + moduleid + ")");
        renderJson(columns);
    }

    @RequiresPermissions(value={"/modules"})
    public void getColumnOne() throws Exception {
        Integer columnsid=getParaToInt("columnsid");
        List<Record> columns = Db.find("SELECT t.id,t.column_comment as name FROM `columns` t WHERE t.id = ?",columnsid);
        renderJson(columns);
    }

    /**
     * 排序字段
     */
    @RequiresPermissions(value={"/modules"})
    public void saveOrderby() throws Exception {
        Long columnsid = getParaToLong("columnsid");
        Long moduleid = getParaToLong("moduleid");
        Integer type = getParaToInt("type");
        renderJson(service.saveOrderby(columnsid,moduleid,type));
    }

    /**
     * 获取排序列
     */
    @RequiresPermissions(value={"/modules"})
    public void getOrders() throws Exception {
        Long moduleid = getParaToLong("moduleid");
        Page<Order> paginate = Order.dao.paginate(getPage(), getRows(),moduleid,getOrderbyStr());
        DataGridModel result = DataGridModelUtils.toDataGridView(paginate);
        renderJson(result);
    }

    @RequiresPermissions(value={"/modules"})
    public void updateOrderby() throws Exception {
        Long orderid = getParaToLong("orderid");
        Long columnsid = getParaToLong("columnsid");
        Long moduleid = getParaToLong("moduleid");
        Integer type = getParaToInt("type");
        renderJson(service.updateOrderby(orderid,columnsid,moduleid,type));
    }

    /**
     *删除自定义排序
     */
    @RequiresPermissions(value={"/modules"})
    public void deleteOrderby() throws Exception {
        Long orderid = getParaToLong("id");
        renderJson(Order.dao.findById(orderid).delete());
    }

	@RequiresPermissions(value={"/modules"})
	public void setIsInterface() throws Exception {
		String id = getPara("id");
		Integer status = getParaToInt("status");
		renderJson(service.setIsInterface(id, status));
	}

	@RequiresPermissions(value={"/modules"})
	public void interfaceSeting() throws Exception {
		Long moduleid = getParaToLong("moduleid");
        Modules modules = service.findById(moduleid);
        setAttr("moduleid", moduleid);
        setAttr("item", modules);
        if(modules.getToken()!=null && modules.getToken().trim().indexOf(":")>0){
			String[] split = modules.getToken().split(":");
			setAttr("tokenKey", split[0]);
			setAttr("tokenValue", split[1]);
		}else{
			setAttr("tokenKey", "");
			setAttr("tokenValue", "");
		}
		setAttr("tokenPosition", DictData.dao.getData("tokenPosition"));
		setAttr("requestType", DictData.dao.getData("requestType"));
		setAttr("encryptType", DictData.dao.getData("encryptType"));
		setAttr("encryptColumn", DictData.dao.getData("encryptColumn"));
		render("interfaceSeting.html");
	}
}
